import { data } from "./data.js";

const imgs = document.getElementById("imgs");
const sizeBar = document.getElementById("side-bar");

// 存储我们创建的图片元素
let imgsDom = [];

// 存储我们创建的导航元素
let navDom = [];

// 记录当前活跃的图片和导航
let activeImg = null;
let activeNav = null;


for (let i = 0; i < data.length; i++) {
    let item = data[i];
    let tagA = document.createElement("a");
    tagA.setAttribute('href', '#');
    tagA.style.backgroundColor = item.bg;
    tagA.style.backgroundImage = `url("${item.img}")`
    imgs.appendChild(tagA);
    imgsDom.push(tagA);

    let tagNav = document.createElement("a");
    tagNav.setAttribute('href', '#');
    tagNav.className = 'nav';
    tagNav.setAttribute('title', item.title + ':' + item.desc);
    tagNav.innerHTML = `<span>${item.title}</span>${item.desc}`;
    sizeBar.appendChild(tagNav);
    navDom.push(tagNav);

    // 初始化第一个元素让他展示
    if (i == 0) {
        tagA.setAttribute('class', 'active');
        tagNav.setAttribute('class', 'active');
        activeImg = tagA;
        activeNav = tagNav;
    }

    tagNav.onmouseenter = function () {
        clearInterval(timer);
        // 把原来活跃的图片和导航取消
        activeImg.setAttribute('class', '');
        activeNav.setAttribute('class', 'nav');
        // 把当前被鼠标选中的导航和图片展示
        tagA.setAttribute('class', 'active');
        tagNav.setAttribute('class', 'active');

        // 记录最新的导航和图片
        activeImg = tagA;
        activeNav = tagNav;
    }
    tagNav.onmouseleave = function () {
        timer = setInterval(move, 1500);
    };
}

// 自己动

function move() {
    activeImg.setAttribute('class', '');
    activeNav.setAttribute('class', 'nav');
    // 找到当前元素的下一个
    let index = imgsDom.indexOf(activeImg);
    if (index == data.length - 1) {
        activeNav = navDom[0];
        activeImg = imgsDom[0];
    } else {
        activeImg = imgsDom[index + 1];
        activeNav = navDom[index + 1];
    }
    activeImg.setAttribute('class', 'active');
    activeNav.setAttribute('class', 'active');

}
let timer = setInterval(move, 1500);